<!-- 联系人树 -->
<template>
  <div class="contact-tree_box">
    <el-tree
      ref="tree"
      lazy
      :load="loadNode"
      node-key="id"
      :props="defaultProps"
      empty-text=""
      :show-checkbox="showCheckbox"
      @check="checkChange"
    >
      <div
        class="custom-tree-node"
        slot-scope="{ node }"
        :class="{ showCheckbox_user: node.data && node.data.code }"
      >
        <div
          v-if="node.data && node.data.code"
          class="user-box"
          @click="handleUserClick(node.data)"
        >
          <chat-avatar
            :size="24"
            :content="node.data.avatar || node.data.name"
          ></chat-avatar>
          <span class="name">{{ node.data.name }}({{ node.data.code }})</span>
        </div>
        <div v-else>{{ node.data.name }}</div>
      </div>
    </el-tree>
  </div>
</template>

<script>
import { getDeparmentTree } from "@/api/common"
import { isEmpty } from "@/utils/validate"
import { mapGetters, mapState } from "vuex"
import { getUserList } from "@/api/user"
import chatAvatar from "./avatar.vue"
export default {
  components: { chatAvatar },
  model: {
    prop: "userList",
    event: "check"
  },
  props: {
    showCheckbox: {
      type: Boolean,
      default: true
    },
    isRemote: {
      type: Boolean,
      default: false
    },
    departList: {
      type: Array,
      default: () => {
        return []
      }
    },
    userList: {
      type: Array,
      default: () => {
        return []
      }
    },
    operateType: {
      type: String,
      default: "create"
    }
  },

  mounted() {
    this.$refs.tree.setCheckedNodes(this.userList)
  },
  data() {
    return {
      isEmpty,
      rootNode: null,
      rootResolve: null
    }
  },
  computed: {
    ...mapState({
      treeList: (state) => state.departTreeList
    }),
    ...mapGetters(["currentGroupMemberList"]),
    defaultProps() {
      return {
        children: "children",
        label: "name",
        disabled: (data, node) => {
          if (node.data && node.data.code) {
            return this.isDisabled(node.data)
          } else {
            return true
          }
        },
        isLeaf: (data, node) => {
          return node.data && node.data.code ? true : false
        }
      }
    }
  },
  methods: {
    async loadNode(node, resolve) {
      if (node.level == 0) {
        this.rootNode = node
        this.rootResolve = resolve
        if (this.isRemote) {
          resolve(this.departList)
        } else {
          resolve(this.treeList)
        }
      } else {
        const { data: deparData } = await getDeparmentTree({
          filter: {
            parentId: node.data.id
          }
        })
        const { data: userData } = await getUserList({
          filter: {
            departmentCode: node.data.id
          }
        })
        const users = userData.map(
          ({
            code,
            name,
            avatar,
            departmentName,
            departmentCode,
            onDutyPhone,
            phone,
            workPhone,
            motto,
            id
          }) => {
            return {
              code,
              name,
              avatar,
              departmentName,
              departmentCode,
              onDutyPhone,
              phone,
              workPhone,
              motto,
              id
            }
          }
        )
        resolve([...users, ...deparData])
        this.$refs.tree.setCheckedNodes(this.userList)
      }
    },
    checkChange(cur, e) {
      let list = []
      if (cur.code) {
        list = this.userList.filter((item) => item.code !== cur.code)
      }

      const arr = this.unique([
        ...e.checkedNodes.filter((item) => item.code),
        ...list
      ])
      this.$emit("check", JSON.parse(JSON.stringify(arr)))
    },

    unique(arr) {
      const res = new Map()
      return arr.filter((item) => !res.has(item.code) && res.set(item.code, 1))
    },
    handleUserClick(data) {
      this.$emit("userChange", data)
    },
    isDisabled(user) {
      return (
        user.id == this.$store.state.userInfo.userId ||
        (this.operateType === "add" &&
          this.currentGroupMemberList.some((item) => item.id == user.id))
      )
    }
  },
  watch: {
    userList: {
      handler(val) {
        this.$refs.tree.setCheckedNodes(val)
      },
      deep: true
    },
    departList: {
      handler(val) {
        this.rootNode.childNodes = []
        this.loadNode(this.rootNode, this.rootResolve)
      },
      deep: true
    }
  }
}
</script>
<style lang="less">
.contact-tree_box {
  .el-tree-node__content {
    height: auto;
    font-size: 14px;
    color: #333333;
    .personal_box {
      display: flex;
      align-items: center;
    }
    .tree_item {
      margin: 5px 0;
      .avatar_box {
        padding-right: 5px;
      }
    }

    .user-box {
      display: flex;
      align-items: center;
      padding: 5px 0;
      .name {
        padding-left: 5px;
      }
    }
  }

  .el-checkbox__input.is-disabled > .el-checkbox__inner {
    display: none;
  }

  .el-checkbox.is-disabled {
    display: none;
    // .user-box {
    //   padding-left: 19.5px !important;
    // }
  }
  .el-checkbox.is-disabled + div.showCheckbox_user {
    padding-left: 23px;
    color: #ccc;
  }
  .is-checked .user-box {
    color: rgb(var(--color-primary));
  }
}
</style>
